<?php

namespace App\Http\Resources;

use App\Models\Permission;
use Illuminate\Http\Resources\Json\ResourceCollection;
use phpDocumentor\Reflection\Types\Boolean;

class BaseResourceCollection extends ResourceCollection
{
    /**
     * @var bool
     */
    protected $needPaginate = true;

    /**
     * @var bool
     */
    protected $needPermission = true;

    /**
     * @var string
     */
    protected $prefix1d = 'api/';

    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'links'         => $this->when($this->needPaginate, function () {
                return [
                    'first_page_url' => $this->url(1),
                    'last_page_url'  => $this->url($this->lastPage()),
                    'next_page_url'  => $this->nextPageUrl(),
                    'prev_page_url'  => $this->previousPageUrl()
                ];
            }),
            'meta'          => $this->when($this->needPaginate, function () {
                return [
                    'current_page'  => $this->currentPage(),
                    'from'          => $this->firstItem(),
                    'last_page'     => $this->lastPage(),
                    'path'          => $this->path(),
                    'per_page'      => $this->perPage(),
                    'to'            => $this->lastItem(),
                    'total'         => $this->total()
                ];
            }),
            'permissions'   => $this->when($this->needPermission, function () use ($request) {
                return $this->getOperationPermissions($request);
            })
        ];
    }

    /**
     * 获取可操作权限
     * @param $request
     * @return array
     */
    public function getOperationPermissions($request)
    {
        $result = [];
        $name = str_replace($this->prefix1d, '', trim($request->path(), '/'));
        $permission = Permission::where('name', $name)->first();
        if (!$permission) {
            return $result;
        }
        $result = Permission::where('parent_id', $permission->id)->pluck('name')->map(function ($item) use ($name) {
            return str_replace($name . '/', '', $item);
        });
        return $result;
    }

    /**
     * 设置是否需要分页数据
     * @param bool $value
     * @return $this
     */
    public function setNeedPaginate(bool $value)
    {
        $this->needPaginate = $value;
        return $this;
    }

    /**
     * 设置是否需要检查权限数据
     * @param bool $value
     * @return $this
     */
    public function setNeedPermission(bool $value)
    {
        $this->needPermission = $value;
        return $this;
    }
}
